package com.blqy.fr.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.blqy.fr.common.annotation.BlQyLogin;
import com.blqy.fr.common.execption.BlQyException;
import com.blqy.fr.common.result.ResultCodeEnum;
import com.blqy.fr.common.util.AuthContextHolder;
import com.blqy.fr.model.user.TeamUser;
import com.blqy.fr.user.mapper.TeamUserMapper;
import com.blqy.fr.user.service.TeamInfoService;
import com.blqy.fr.user.service.TeamUserService;
import com.blqy.fr.vo.team.TeamListItemVo;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TeamUserServiceImpl implements TeamUserService {

    @Autowired
    private TeamUserMapper teamUserMapper;

    @Override
    @Transactional
    @BlQyLogin
    public void switchCurrentTeam(Long teamId) {
        Long userId = AuthContextHolder.getUserId();
        if (userId == null) {
            throw new BlQyException(ResultCodeEnum.LOGIN_AUTH);
        }

        // 1. 校验用户是否属于该团队（state=0 或 1）
        TeamUser target = teamUserMapper.selectOne(
                new LambdaQueryWrapper<TeamUser>()
                        .eq(TeamUser::getUserId, userId)
                        .eq(TeamUser::getTeamId, teamId)
                        .in(TeamUser::getState, 0, 1)
        );
        if (target == null) {
            throw new BlQyException(ResultCodeEnum.DATA_NOT_FOUND);
        }

        // 2. 将用户所有团队的 state 设为 0
        teamUserMapper.update(null,
                new LambdaUpdateWrapper<TeamUser>()
                        .set(TeamUser::getState, 0)
                        .eq(TeamUser::getUserId, userId)
        );

        // 3. 将目标团队设为 state = 1
        teamUserMapper.update(null,
                new LambdaUpdateWrapper<TeamUser>()
                        .set(TeamUser::getState, 1)
                        .eq(TeamUser::getUserId, userId)
                        .eq(TeamUser::getTeamId, teamId)
        );
    }

    @Override
    public List<TeamListItemVo> getTeamList(Long userId) {
        if (userId == null) {
            throw new BlQyException(ResultCodeEnum.LOGIN_AUTH);
        }
        return teamUserMapper.selectTeamListByUserId(userId);
    }

    @Override
    @BlQyLogin
    public Long getTeamIdByUserId(Long userId) {
        if (userId == null) {
            throw new BlQyException(ResultCodeEnum.LOGIN_AUTH);
        }
        return teamUserMapper.selectTeamIdByUserId(userId);
    }
}
